package com.registration.service;

import com.registration.bean.OrderBean;
import com.registration.bean.PaymentBean;
import com.registration.mapper.OrderMapper;
import com.registration.mapper.PaymentMapper;
import com.registration.mapper.ScheduleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private PaymentMapper paymentMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ScheduleMapper scheduleMapper;

    /**
     * 查询就诊人待处理的支付项
     * @param patientId 就诊人ID
     * @return 待处理的支付项列表
     */
    @Override
    public List<PaymentBean> selectPendingPaymentItemsByUserId(Integer patientId) {
        //支付状态（0 - 处理中，1 - 成功，2 - 失败）
        return paymentMapper.selectPendingPaymentItemsByUserId(patientId, 0);
    }

    /**
     * 查询就诊人支付记录
     * @param patientId 就诊人ID
     * @return 支付记录列表
     */
    @Override
    public List<PaymentBean> selectPaymentRecordsByUserId(Integer patientId) {
        return paymentMapper.selectPaymentRecordsByUserId(patientId,Arrays.asList(1, 2));
    }

    /**
     * 插入支付记录
     * @param paymentBean 支付信息
     * @return 插入结果
     * selectOrderDetailById  order表中获取订单详情
     */

    public int insertPaymentRecord(PaymentBean paymentBean) {
    // 验证必要字段
    if (paymentBean.getOrder_id() == null) {
        throw new RuntimeException("订单ID不能为空");
    }
    if (paymentBean.getUser_id() == null) {
        throw new RuntimeException("用户ID不能为空");
    }
    if (paymentBean.getPatient_id() == null) {
        throw new RuntimeException("患者ID不能为空");
    }
    if (paymentBean.getAmount() == null) {
        throw new RuntimeException("金额不能为空");
    }
    if (paymentBean.getPay_no() == null || paymentBean.getPay_no().isEmpty()) {
        throw new RuntimeException("支付编号不能为空");
    }

    return paymentMapper.insertPaymentRecord(paymentBean);
}

    /**
     * 修改支付项状态
     * @param record_id 支付项id
     * @return 修改结果
     */
    @Override
    public int updatePaymentItemStatus(Integer record_id) {
        return paymentMapper.updatePaymentItemStatus(record_id);
    }

    /**
     * 根据订单id获取待支付项
     * @param orderId 订单id
     * @return 待支付列表
     */
    @Override
    public List<PaymentBean> selectPendingItemsByOrderId(Integer orderId) {
        return paymentMapper.selectPendingItemsByOrderId(orderId);
    }

    /**
     * 根据交易号获取支付记录
     * @param tradeNo 交易号
     * @return 支付记录
     */
    @Override
    public PaymentBean selectPaymentByTradeNo(String tradeNo) {
        return paymentMapper.selectPaymentByTradeNo(tradeNo);
    }

    /**
     * 申请退款
     * @param paymentBean 退款信息
     * @return 影响行数
     */
    @Override
    public int applyRefund(PaymentBean paymentBean) {
        return paymentMapper.applyRefund(paymentBean);
    }

    /**
     * 处理支付结果通知
     * @param paymentBean 支付结果通知信息
     * @return 是否处理成功
     */
    @Override
    public boolean processPaymentNotify(PaymentBean paymentBean) {
        return paymentMapper.updatePaymentItemStatus(paymentBean.getOrder_id()) > 0;
    }

    /**
     * 查询超时未处理的支付项
     * @param timeoutMinutes 超时时间（分钟）
     * @return 超时未处理的支付项列表
     */
    @Override
    public List<PaymentBean> selectTimeoutPendingPayments(int timeoutMinutes) {
        LocalDateTime timeoutTime = LocalDateTime.now().minusMinutes(timeoutMinutes);
        return paymentMapper.selectPendingPaymentsBeforeTime(timeoutTime);
    }

    /**
     * 取消超时未处理的支付项
     * @param timeoutMinutes 超时时间（分钟）
     * @return 影响行数
     */
    @Override
    @Transactional
    public int cancelTimeoutPendingPayments(int timeoutMinutes) {
        // 1. 查询超时的支付记录
        List<PaymentBean> timeoutPayments = selectTimeoutPendingPayments(timeoutMinutes);
        int count = 0;

        for (PaymentBean payment : timeoutPayments) {
            // 2. 更新支付状态为超时取消
            int rows = paymentMapper.updatePaymentStatus(payment.getRecord_id(), 2); // 2表示取消状态
            if (rows > 0) {
                // 3. 获取关联的订单
                OrderBean order = orderMapper.selectOrderById(payment.getOrder_id());
                if (order != null && order.getSchedule_id() != null) {
                    // 4. 释放号源
                    scheduleMapper.increaseQuota(order.getSchedule_id());
                }
                count++;
            }
        }
        return count;
    }











}

